<template>
  <div>
    <h2>财务报表</h2>
    <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
      <!-- 陪玩财务报表 -->
      <el-tab-pane label="陪玩财务" name="playmate">
        <el-form :inline="true" :model="playmateQuery" class="demo-form-inline">
          <el-form-item label="年份">
            <el-input-number v-model="playmateQuery.year" :min="2025" :max="2100" placeholder="年份"></el-input-number>
          </el-form-item>
          <el-form-item label="期间类型">
            <el-select v-model="playmateQuery.periodType" placeholder="请选择期间类型" @change="handlePeriodTypeChange(playmateQuery)">
              <el-option label="季度" :value="1"></el-option>
              <el-option label="半年度" :value="2"></el-option>
              <el-option label="年度" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="期间" v-if="playmateQuery.periodType && playmateQuery.periodType !== 3">
            <el-select v-model="playmateQuery.period" placeholder="请选择期间">
              <el-option 
                v-for="item in getPeriodOptions(playmateQuery.periodType)" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryPlaymateFinancial">查询</el-button>
          </el-form-item>
        </el-form>
        
        <el-table :data="playmateFinancialData" border>
          <el-table-column prop="playmateId" label="陪玩ID" width="80"></el-table-column>
          <el-table-column prop="playmateNickname" label="陪玩昵称" width="120"></el-table-column>
          <el-table-column prop="totalIncome" label="总收入" width="120">
            <template #default="scope">{{ scope.row.totalIncome | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="totalSpent" label="总支出" width="120">
            <template #default="scope">{{ scope.row.totalSpent | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="finalBalance" label="账户余额" width="120">
            <template #default="scope">{{ scope.row.finalBalance | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="incomeCount" label="收入笔数" width="100"></el-table-column>
          <el-table-column prop="spentCount" label="支出笔数" width="100"></el-table-column>
          <el-table-column prop="firstRecordTime" label="首笔流水时间" width="180"></el-table-column>
          <el-table-column prop="lastRecordTime" label="最后流水时间" width="180"></el-table-column>
        </el-table>
        
        <el-pagination
          @size-change="handlePlaymateSizeChange"
          @current-change="handlePlaymateCurrentChange"
          :current-page="playmateQuery.page"
          :page-sizes="[10, 20, 50]"
          :page-size="playmateQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="playmateFinancialTotal">
        </el-pagination>
      </el-tab-pane>

      <!-- 老板财务报表 -->
      <el-tab-pane label="老板财务" name="boss">
        <el-form :inline="true" :model="bossQuery" class="demo-form-inline">
          <el-form-item label="年份">
            <el-input-number v-model="bossQuery.year" :min="2025" :max="2100" placeholder="年份"></el-input-number>
          </el-form-item>
          <el-form-item label="期间类型">
            <el-select v-model="bossQuery.periodType" placeholder="请选择期间类型" @change="handlePeriodTypeChange(bossQuery)">
              <el-option label="季度" :value="1"></el-option>
              <el-option label="半年度" :value="2"></el-option>
              <el-option label="年度" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="期间" v-if="bossQuery.periodType && bossQuery.periodType !== 3">
            <el-select v-model="bossQuery.period" placeholder="请选择期间">
              <el-option 
                v-for="item in getPeriodOptions(bossQuery.periodType)" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryBossFinancial">查询</el-button>
          </el-form-item>
        </el-form>
        
        <el-table :data="bossFinancialData" border>
          <el-table-column prop="bossId" label="老板ID" width="80"></el-table-column>
          <el-table-column prop="bossNickname" label="老板昵称" width="120"></el-table-column>
          <el-table-column prop="totalSpent" label="总消费" width="120">
            <template #default="scope">{{ scope.row.totalSpent | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="finalBalance" label="账户余额" width="120">
            <template #default="scope">{{ scope.row.finalBalance | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="totalOrderCount" label="订单总数" width="100"></el-table-column>
          <el-table-column prop="totalTip" label="总打赏" width="120">
            <template #default="scope">{{ scope.row.totalTip | formatMoney }}</template>
          </el-table-column>
          <el-table-column prop="firstSpentTime" label="首次消费时间" width="180"></el-table-column>
          <el-table-column prop="lastSpentTime" label="最后消费时间" width="180"></el-table-column>
        </el-table>
        
        <el-pagination
          @size-change="handleBossSizeChange"
          @current-change="handleBossCurrentChange"
          :current-page="bossQuery.page"
          :page-sizes="[10, 20, 50]"
          :page-size="bossQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="bossFinancialTotal">
        </el-pagination>
      </el-tab-pane>

      <!-- 平台财务报表 -->
      <el-tab-pane label="平台财务" name="platform">
        <el-form :inline="true" :model="platformQuery" class="demo-form-inline">
          <el-form-item label="年份">
            <el-input-number v-model="platformQuery.year" :min="2025" :max="2100" placeholder="年份"></el-input-number>
          </el-form-item>
          <el-form-item label="期间类型">
            <el-select v-model="platformQuery.periodType" placeholder="请选择期间类型" @change="handlePeriodTypeChange(platformQuery)">
              <el-option label="季度" :value="1"></el-option>
              <el-option label="半年度" :value="2"></el-option>
              <el-option label="年度" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="期间" v-if="platformQuery.periodType && platformQuery.periodType !== 3">
            <el-select v-model="platformQuery.period" placeholder="请选择期间">
              <el-option 
                v-for="item in getPeriodOptions(platformQuery.periodType)" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryPlatformFinancial">查询</el-button>
          </el-form-item>
        </el-form>
        
        <el-card>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">总订单金额</div>
                <div class="stat-value">{{ platformData.totalOrderMoney | formatMoney }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">总打赏金额</div>
                <div class="stat-value">{{ platformData.totalTipMoney | formatMoney }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">平台抽佣</div>
                <div class="stat-value">{{ platformData.totalCommission | formatMoney }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-label">租户收入</div>
                <div class="stat-value">{{ platformData.totalTenantIncome | formatMoney }}</div>
              </div>
            </el-col>
          </el-row>
          
          <div style="margin-top: 20px;">
            <h3>订单统计</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="总订单数">{{ platformData.totalOrderCount || 0 }}</el-descriptions-item>
               <el-descriptions-item label="平均订单金额">{{ platformData.averageOrderAmount || 0 }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div style="margin-top: 20px;">
            <h3>收入趋势</h3>
            <!-- 替换为ECharts容器 -->
            <div id="incomeTrendChart" style="width: 100%; height: 300px;"></div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import adminApi from "@/http/adminApi";
// 引入ECharts核心模块
import * as echarts from 'echarts';

export default {
  data() {
    return {
      activeTab: 'playmate',
      // 查询参数
      playmateQuery: {
        tenantId: 1,
        year: new Date().getFullYear(),
        periodType: null,
        period: null,
        page: 1,
        pageSize: 10
      },
      bossQuery: {
        tenantId: 1,
        year: new Date().getFullYear(),
        periodType: null,
        period: null,
        page: 1,
        pageSize: 10
      },
      platformQuery: {
        tenantId: 1,
        year: new Date().getFullYear(),
        periodType: null,
        period: null
      },
      // 数据
      playmateFinancialData: [],
      bossFinancialData: [],
      platformData: {
        dailyIncome: {}
      },
      // 分页总数
      playmateFinancialTotal: 0,
      bossFinancialTotal: 0,
      // ECharts实例
      incomeTrendChartInstance: null
    }
  },
  filters: {
    formatMoney(value) {
      if (!value) return '0.00';
      return Number(value).toFixed(2);
    }
  },
  methods: {
    handleTabChange(tab) {
      switch(tab.name) {
        case 'playmate':
          this.queryPlaymateFinancial();
          break;
        case 'boss':
          this.queryBossFinancial();
          break;
        case 'platform':
          this.queryPlatformFinancial();
          // 切换到平台标签时初始化图表
          this.$nextTick(() => {
            this.initIncomeTrendChart();
          });
          break;
      }
    },
    // 查询陪玩财务数据
    queryPlaymateFinancial() {
      adminApi.getPlaymateFinancialReport(this.playmateQuery).then(res => {
        this.playmateFinancialData = res.data.list;
        this.playmateFinancialTotal = res.data.total;
      }).catch(err => {
        console.error('查询陪玩财务数据失败', err);
      });
    },
    // 查询老板财务数据
    queryBossFinancial() {
      adminApi.getBossFinancialReport(this.bossQuery).then(res => {
        this.bossFinancialData = res.data.list;
        this.bossFinancialTotal = res.data.total;
      }).catch(err => {
        console.error('查询老板财务数据失败', err);
      });
    },
    // 查询平台财务数据
    queryPlatformFinancial() {
      adminApi.getPlatformFinancialReport(this.platformQuery).then(res => {
        this.platformData = res.data || { dailyIncome: {} };
        // 查询数据后更新图表
        this.$nextTick(() => {
          this.initIncomeTrendChart();
        });
      }).catch(err => {
        console.error('查询平台财务数据失败', err);
      });
    },
    // 分页处理
    handlePlaymateSizeChange(val) {
      this.playmateQuery.pageSize = val;
      this.queryPlaymateFinancial();
    },
    handlePlaymateCurrentChange(val) {
      this.playmateQuery.page = val;
      this.queryPlaymateFinancial();
    },
    handleBossSizeChange(val) {
      this.bossQuery.pageSize = val;
      this.queryBossFinancial();
    },
    handleBossCurrentChange(val) {
      this.bossQuery.page = val;
      this.queryBossFinancial();
    },
    // 处理期间类型变化
    handlePeriodTypeChange(query) {
      query.period = null;
    },
    // 获取期间选项
    getPeriodOptions(periodType) {
      if (periodType === 1) {
        // 季度选项
        return [
          { label: '第一季度', value: 1 },
          { label: '第二季度', value: 2 },
          { label: '第三季度', value: 3 },
          { label: '第四季度', value: 4 }
        ];
      } else if (periodType === 2) {
        // 半年度选项
        return [
          { label: '上半年', value: 1 },
          { label: '下半年', value: 2 }
        ];
      }
      return [];
    },
    // 初始化收入趋势图表
    initIncomeTrendChart() {
      // 销毁已有实例，避免重复创建
      if (this.incomeTrendChartInstance) {
        this.incomeTrendChartInstance.dispose();
      }
      
      // 创建图表实例
      this.incomeTrendChartInstance = echarts.init(document.getElementById('incomeTrendChart'));
      
      // 准备图表数据
      const xAxisData = Object.keys(this.platformData.dailyIncome);
      const seriesData = Object.values(this.platformData.dailyIncome);
      
      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c} 元'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 元'
          }
        },
        series: [{
          name: '收入金额',
          type: 'line',
          data: seriesData,
          smooth: true,
          lineStyle: {
            width: 2
          },
          itemStyle: {
            radius: 4
          }
        }]
      };
      
      // 设置图表选项
      this.incomeTrendChartInstance.setOption(option);
      
      // 监听窗口大小变化，自动调整图表尺寸
      window.addEventListener('resize', () => {
        if (this.incomeTrendChartInstance) {
          this.incomeTrendChartInstance.resize();
        }
      });
    }
  },
  mounted() {
    this.queryPlaymateFinancial();
  },
  beforeUnmount() {
    // 组件卸载时销毁图表实例，释放资源
    if (this.incomeTrendChartInstance) {
      this.incomeTrendChartInstance.dispose();
      this.incomeTrendChartInstance = null;
    }
  }
}
</script>